package com.xneure.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.time.FastDateFormat;

/**
 * <p>
 * 日期处理工具
 * </p>
 * <p>
 * Copyright: 版权所有<br>
 *
 * @author 张军
 * @version 2016年4月17日
 */
public class DateUtil{
	public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
	public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss";
	public static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy/MM/dd HH:mm:ss.SSS";
	private static final ThreadLocal<Map<String,SimpleDateFormat>> cache = new ThreadLocal<Map<String,SimpleDateFormat>>(){
		@Override
		protected Map<String,SimpleDateFormat> initialValue(){
			return new HashMap<String,SimpleDateFormat>();
		}
	};

	public static String timeFormat(Date date){
		return FastDateFormat.getInstance(DEFAULT_TIME_FORMAT).format(date);
	}
	public static String dateFormat(Date date){
		return FastDateFormat.getInstance(DEFAULT_DATE_TIME_FORMAT).format(date);
	}

	public static Date autoFormat(String date){
		if(date.contains(":")){// 时间
			if(date.contains(" ")){ // 时间 日期
				if(date.contains(".")){ // 包含毫秒
					return strToDate(date,DEFAULT_TIMESTAMP_FORMAT);
				}
				return strToDate(date,DEFAULT_DATE_TIME_FORMAT);
			}
			return strToDate(date,DEFAULT_TIME_FORMAT);
		}else{
			return strToDate(date,DEFAULT_DATE_FORMAT);
		}
	}

	public static String dateFormat(Date date,String format){
		return FastDateFormat.getInstance(format).format(date);
	}

	public static Date strToDate(String date,String format){
		Map<String,SimpleDateFormat> sdf = cache.get();
		SimpleDateFormat dateFormat = sdf.get(format);
		if(null == dateFormat){
			synchronized(sdf){
				if(sdf.containsKey(format) == false){
					dateFormat = new SimpleDateFormat(format);
					sdf.put(format,dateFormat);
				}
			}
		}
		try{
			if(null!=dateFormat) {
				return dateFormat.parse(date.replaceAll("-","/").replace("秒","").replaceAll("小时|分|分钟|/g",":"));
			}else {
				return null;
			}
		}catch(ParseException e){
			return null;
		}
	}
}
